package protoType;

import java.io.*;

public class Sheep implements Cloneable,Serializable{

    public String name;
    private int age;
    private String address;
    private String color = "白色";
    public Sheep friend;

    public Sheep() {
    }

    public Sheep(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }
    /*//浅拷贝，数据类型是基本数据类的成员变量，浅拷贝会直接进行值传递
    //对于数据类型是引用数据类型的成员变量，比如是字符串或则某个类的对象，那么会进行引用传递
    //也就是只是将改成员变量的引用值（内存地址）复制一份给新的对象，
    // 实际上克隆对象的引用成员变量与原型的指向同一个实例
    @Override
    public Sheep clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return (Sheep) clone;
    }*/
/*
    //深拷贝，方式1：使用引用成员属性的clone方法，再次拷贝引用成员属性
    @Override
    public Sheep clone() {
        Sheep sheep = null;
        try {
            sheep = (Sheep) super.clone();
            sheep.friend = (Sheep) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return sheep;
    }*/

    /*
    * 深拷贝方式2：通过对象的序列化实现，这种方式会将所有堆内存中的属性重新拷贝，推荐使用
    * */

    public Sheep deepClone() throws IOException {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        Sheep sheep = null;
        try(bos;oos;bis;ois) {
            sheep = (Sheep) ois.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return sheep;
    }

}
